package logic

import (
	"context"
	"goods-ctrl/goodsrpc/goodsrpc"
	"goods-ctrl/goodsrpc/internal/svc"
	"goods-ctrl/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsAddLogic) GoodsAdd(in *goodsrpc.GoodsAddRequest) (*goodsrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line

	begin := model.DB.Begin()
	var brand model.Brand
	if brand.Name == "" {
		brand := model.Brand{

			Name: brand.Name,
		}
		err := begin.Create(&brand).Error
		if err != nil {
			begin.Rollback()
			return nil, err
		}
	}

	var class model.Class
	if class.Name == "" {
		class := model.Class{

			Name: class.Name,
		}
		err := begin.Create(&class).Error
		if err != nil {
			begin.Rollback()
			return nil, err
		}
	}

	good := model.Goods{

		Name:    in.Name,
		Age:     in.Age,
		BrandId: int(brand.ID),
		ClassId: int(class.ID),
	}
	err := begin.Create(&good).Error
	if err != nil {
		begin.Rollback()
		return nil, err
	}
	begin.Commit()

	return &goodsrpc.GoodsAddResponse{
		Id: int64(good.ID),
	}, nil
}
